package codeMaker;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.filechooser.FileSystemView;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import constant.ChildWindowConstant;
import constant.CodeConstant;
import constant.Constant;
import entity.Parameters;
import main.MainMethod;
import util.DBUtils;

public class MakeCode {

    private JFrame frmv;
    private JTextField projectName;
    private JLabel proinfo;
    private JComboBox<String> framework;
    private JComboBox<String> databaseType;
    private JTextField dataBaseIp;
    private JTextField dataBasePort;
    private JTextField dataBasePwd;
    private JTextField dataBaseName;
    private JTextField dataBaseUserName;
    private JTextField outPath;
    private JTextField tableName;

    /**
     * Launch the application.
     */
    // SubstanceCeruleanLookAndFeel 蓝色简约
    // SubstanceCremeCoffeeLookAndFeel 咖啡俏皮
    // SubstanceGeminiLookAndFeel 黑绿简约
    // SubstanceGraphiteLookAndFeel 灰黑控
    // SubstanceModerateLookAndFeel 白色简约
    // SubstanceOfficeBlack2007LookAndFeel office2007
    // SubstanceBusinessBlackSteelLookAndFeel 商务黑
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    // UIManager.setLookAndFeel(com.jtattoo.plaf.mcwin.McWinLookAndFeel.class.getName());
                    UIManager.setLookAndFeel(
                            org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel.class.getName());
                    JFrame.setDefaultLookAndFeelDecorated(true);
                    JDialog.setDefaultLookAndFeelDecorated(true);
                    MakeCode window = new MakeCode();
                    Constant.frmv = window.frmv;
                    window.frmv.setVisible(true);

                    File ipFile = new File(Constant.gitIpAdressFilePath);

                    if (!ipFile.exists()) {
                        JOptionPane.showMessageDialog(window.frmv,
                                "代码生成器客户端有重大更新，请前往公众号“螺旋编程极客”或网址 http://www.zrxlh.top:8088/coreCode/ 下载最新版方可使用，带来不便，深表歉意！",
                                "提示", JOptionPane.WARNING_MESSAGE);
                        System.exit(0);
                    }

                    File gitConfigFile = new File(Constant.gitConfigFilePath);

                    if (!gitConfigFile.exists()) {
                        JOptionPane.showMessageDialog(window.frmv,
                                "代码生成器客户端更新啦，优化了资源拉取速度，在 http://www.zrxlh.top:8088/coreCode/ 下载最新版方可使用！", "提示",
                                JOptionPane.WARNING_MESSAGE);
                    }

                    JOptionPane.showMessageDialog(window.frmv,
                            "本次更新：多表配置优化，新增自定义实体功能（高级配置——》自定义实体）！" + CodeConstant.NEW_LINE
                                    + "目前已支持一键生成项目导入eclipse/idea运行，不断完善中！" + CodeConstant.NEW_LINE
                                    + "后续更新：更多个性化配置，更加灵活的生成代码！" + CodeConstant.NEW_LINE + "敬请期待！",
                            "提示", JOptionPane.INFORMATION_MESSAGE);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MakeCode() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmv = new JFrame();
        frmv.setIconImage(Toolkit.getDefaultToolkit().getImage(MakeCode.class.getResource(
                "/org/pushingpixels/substance/internal/contrib/randelshofer/quaqua/images/color_wheel.png")));
        frmv.setResizable(false);
        frmv.setTitle("代码生成器V2.16 by 小螺旋丸");
        frmv.setBounds(100, 100, 732, 631);
        frmv.setLocationRelativeTo(null);
        frmv.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lblNewLabel = new JLabel("项目名称");

        projectName = new JTextField();
        projectName.setColumns(10);

        JLabel label = new JLabel("后台框架");

        framework = new JComboBox<String>();
        framework.setModel(new DefaultComboBoxModel<String>(new String[]{"springBoot", "ssm"}));

        JLabel label_1 = new JLabel("数据库类型");

        databaseType = new JComboBox<String>();
        databaseType.setModel(
                new DefaultComboBoxModel<String>(new String[]{"mysql", "postgresql", "oracle", "sqlserver"}));

        JLabel lblip = new JLabel("数据库IP");

        dataBaseIp = new JTextField();
        dataBaseIp.setColumns(10);

        JLabel label_2 = new JLabel("端口");

        dataBasePort = new JTextField();
        dataBasePort.setColumns(10);

        JLabel label_3 = new JLabel("密码");

        dataBasePwd = new JTextField();
        dataBasePwd.setColumns(10);

        proinfo = new JLabel();
        proinfo.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 14));
        proinfo.setText(
                "<html><body>此工具可以根据配置灵活生成从前台到后台的所有代码！<br/>\r\n简约，智能，高效！<br/>\r\n不断升级中。。欢迎提出您的宝贵意见！<br/>\r\n</body></html>");

        JLabel lblNewLabel_1 = new JLabel("*");
        lblNewLabel_1.setForeground(Color.RED);

        JLabel lblservicenamesid = new JLabel("数据库名称（SERVICE NAME/SID）");

        dataBaseName = new JTextField();
        dataBaseName.setColumns(10);

        JLabel label_7 = new JLabel("*");
        label_7.setForeground(Color.RED);

        JLabel label_8 = new JLabel("用户名");

        dataBaseUserName = new JTextField();
        dataBaseUserName.setColumns(10);

        JLabel label_9 = new JLabel("*");
        label_9.setForeground(Color.RED);

        JLabel label_10 = new JLabel("项目输出路径");

        outPath = new JTextField();
        outPath.setEditable(false);
        outPath.setColumns(10);

        JLabel label_11 = new JLabel("*");
        label_11.setForeground(Color.RED);

        JButton button = new JButton("选择");
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int flg = jfc.showDialog(new JLabel(), "选择");

                // 如果选择了文件
                if (flg == JFileChooser.APPROVE_OPTION) {
                    File file = jfc.getSelectedFile();
                    outPath.setText(file.getAbsolutePath());
                }
            }
        });

        JLabel label_12 = new JLabel("登录配置");

        final JComboBox<String> loginConfig = new JComboBox<String>();
        loginConfig.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String loginItem = (String) loginConfig.getSelectedItem();

                dealDymaicAndStaticUser(loginItem);

            }

        });
        loginConfig.setModel(new DefaultComboBoxModel<String>(new String[]{"静态用户", "动态用户"}));

        final JButton btnNewButton = new JButton("点击生成");

        JLabel label_13 = new JLabel("数据表（多个用 # 隔开）");

        tableName = new JTextField();
        tableName.setColumns(10);

        JLabel label_17 = new JLabel("前台风格");

        final JComboBox<String> clientStyle = new JComboBox<String>();
        clientStyle.setModel(new DefaultComboBoxModel<String>(
                new String[]{"custom-经典", "flatly-平淡", "journal-杂志", "lumen-立体", "paper-纸质", "readable-书本"}));

        JLabel tips = new JLabel(" ");
        tips.setFont(new Font("宋体", Font.BOLD, 15));

        JLabel lblNewLabel_2 = new JLabel("JS框架");

        JComboBox<String> jsFrameWorkComBox = new JComboBox<String>();
        jsFrameWorkComBox.setModel(new DefaultComboBoxModel<String>(new String[]{"vue", "jquery"}));

        JLabel themeLable = new JLabel("主题设置");

        JComboBox<String> themeComboBox = new JComboBox<>();
        themeComboBox.setModel(new DefaultComboBoxModel<String>(new String[]{"前后端分离响应式", "经典后台Thymleaf版"}));

        // 生代码
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                // 按钮不可用
                btnNewButton.setEnabled(false);
                tips.setText("检查配置 and 代码生成中，请耐心等待。。。");
            }

            @Override
            public void mouseReleased(MouseEvent e) {

                try {

                    String projectNameVal = projectName.getText();
                    if ("".equals(projectNameVal)) {
                        projectNameVal = Constant.projectName;
                    }
                    String frameWorkVal = (String) framework.getSelectedItem();

                    String dataBaseTypeVal = (String) databaseType.getSelectedItem();

                    String clientFrameWorkVal = (String) clientStyle.getSelectedItem();

                    String jsFrameWork = (String) jsFrameWorkComBox.getSelectedItem();

                    String themeVal = (String) themeComboBox.getSelectedItem();

                    if ("sqlserver".equals(dataBaseTypeVal)) {

                        JOptionPane.showMessageDialog(frmv,
                                "暂不支持sqlserver！" + CodeConstant.NEW_LINE + "后续会开放相关支持", "提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }

                    Parameters parameters = checkNeccessary();

                    if (parameters == null) {

                        JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目！", "警告", JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    String loginValue = (String) loginConfig.getSelectedItem();

                    // 获取数据库连接，设置url和driverClass参数和connection
                    if (!"".equals(tableName.getText()) && DBUtils.getConnection(parameters) == null) {

                        JOptionPane.showMessageDialog(frmv, "数据库连接有误，无法查询您配置的表，如果一定要生成，请先清空数据表的输入框再生成！", "警告", JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    if (DBUtils.getConnection(parameters) == null) {
                        JOptionPane.showMessageDialog(frmv, "数据库连接有误，生成后程序将无法正常运行！", "警告", JOptionPane.ERROR_MESSAGE);
                    }

                    String[] tableNameArr = new String[]{};

                    if (!"".equals(tableName.getText())) {
                        tableNameArr = tableName.getText().split("#");
                    }
                    // 检查是否每个表都进行了主键以及数据项的配置

                    String tipStr = "";
                    // 检查每个表是否可以正常连接数据库查询
                    for (int i = 0; i < tableNameArr.length; i++) {
                        List<String> columnNameList = DBUtils.getColumnNameList(dataBaseTypeVal, tableNameArr[i],
                                DBUtils.getConnection(parameters));
                        if (columnNameList != null) {
                            continue;
                        }
                        if (i == tableNameArr.length - 1) {
                            tipStr += tableNameArr[i];
                            break;
                        }
                        tipStr += tableNameArr[i] + ",";
                    }

                    // 如果提示不为空，说明有表名填写出现问题
                    if (!"".equals(tipStr)) {

                        JOptionPane.showMessageDialog(frmv,
                                "查询数据表 " + tipStr + " 时出现未知错误！请仔细检查表名是否配置正确（postgresql需要模式名.表名（除public模式））！表名与表名之前是否使用#隔开！", "错误",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    tipStr = "";
                    for (int i = 0; i < tableNameArr.length; i++) {
                        if (ChildWindowConstant.primaryKeyListMap.get(tableNameArr[i]) != null) {
                            continue;
                        }
                        if (i == tableNameArr.length - 1) {
                            tipStr += tableNameArr[i];
                            break;
                        }
                        tipStr += tableNameArr[i] + ",";
                    }

                    // 如果提示不为空 证明有表没有配置主键
                    if (!"".equals(tipStr)) {

                        JOptionPane.showMessageDialog(frmv, "检测到 " + tipStr + "数据表没有配置主键，请在数据库配置中进行配置！", "提示",
                                JOptionPane.INFORMATION_MESSAGE);

                        // 自动打开数据库配置界面
                        if (ChildWindowConstant.dataBaseConfig == null) {
                            DataBaseConfig.main(parameters);
                        } else {
                            ChildWindowConstant.dataBaseConfig.dispose();
                            ChildWindowConstant.dataBaseConfig = null;
                            DataBaseConfig.main(parameters);
                        }
                        return;
                    }

                    // 配完主键后
                    tipStr = "";
                    for (int i = 0; i < tableNameArr.length; i++) {
                        if (ChildWindowConstant.columnMsgMap.get(tableNameArr[i]).size() != 0) {
                            continue;
                        }
                        if (i == tableNameArr.length - 1) {
                            tipStr += tableNameArr[i];
                            break;
                        }
                        tipStr += tableNameArr[i] + ",";
                    }

                    // 如果不为空 说明有表的字段信息没有进行配置
                    if (!"".equals(tipStr)) {

                        int ifGo = JOptionPane.showConfirmDialog(frmv,
                                "检测到您没有进行表 " + tipStr + " 的数据项配置，将默认查询并展示表的所有的字段项目" + CodeConstant.NEW_LINE
                                        + "由于没有进行配置，字段将按照字段的英文名称展示！" + CodeConstant.NEW_LINE + "是否前去配置？",
                                "提示", JOptionPane.YES_NO_OPTION);
                        if (ifGo == 0) {
                            if (ChildWindowConstant.dataBaseConfig == null) {
                                DataBaseConfig.main(parameters);
                            } else {
                                ChildWindowConstant.dataBaseConfig.dispose();
                                ChildWindowConstant.dataBaseConfig = null;
                                DataBaseConfig.main(parameters);
                            }
                            return;
                        }
                    }

                    // 判断并处理登录用户相关
                    if (!dealDymaicAndStaticUser(loginValue)) {
                        return;
                    }

                    int getCodeConfirmDialog = JOptionPane.showConfirmDialog(frmv,
                            "当前项目名称为：" + ("".equals(projectNameVal) ? "freeout" : projectNameVal)
                                    + CodeConstant.NEW_LINE + "当前前台风格选择为：" + clientFrameWorkVal + CodeConstant.NEW_LINE
                                    + "js框架选择为：" + jsFrameWork + CodeConstant.NEW_LINE + "后台框架选择为：" + frameWorkVal
                                    + CodeConstant.NEW_LINE + "数据库选择为：" + dataBaseTypeVal + CodeConstant.NEW_LINE
                                    + "确认生成吗？？",
                            "提示", JOptionPane.YES_NO_OPTION);

                    if (getCodeConfirmDialog != 0) {
                        return;
                    }

                    // 最后设置共性信息
                    parameters.setProjectNameVal(projectNameVal);
                    parameters.setFrameWorkVal(frameWorkVal);
                    parameters.setClientFrameWorkVal(clientFrameWorkVal);
                    parameters.setMakeModelVal(loginValue);
                    parameters.setJsFrameWork(jsFrameWork);
                    parameters.setThemeVal(themeVal);

                    //System.out.println(parameters);

                    boolean progressFlg = MainMethod.progress(parameters);

                    if (progressFlg) {

                        tips.setText("           代码生成完毕！");
                        String msg = "";
                        if (CodeConstant.oldTheme.equals(themeVal)) {
                            msg = "代码生成完毕，编码为utf-8，导入eclipse/idea访问 http://localhost:8080/项目名/login 即可！"
                                    + CodeConstant.NEW_LINE + "如没有进行数据库登录的配置 ,默认用户名为admin，密码为root"
                                    + CodeConstant.NEW_LINE + "是否打开生产目录？";
                        } else if (CodeConstant.hAdminTheme.equals(themeVal)) {
                            msg = "代码生成完毕（在设置的路径下生成了两个项目），编码为utf-8" + CodeConstant.NEW_LINE
                                    + "后台项目导入eclipse/idea运行，前台项目webClient使用浏览器直接打开login,html（或发布到静态资源服务器）即可！"
                                    + CodeConstant.NEW_LINE + "如没有进行数据库登录的配置 ,默认用户名为admin，密码为root"
                                    + CodeConstant.NEW_LINE + "是否打开生产目录？";
                        }

                        int showConfirmDialog = JOptionPane.showConfirmDialog(frmv, msg, "提示",
                                JOptionPane.YES_NO_OPTION);

                        if (showConfirmDialog == 0) {
                            Desktop.getDesktop().open(new File(parameters.getOutPathVal()));
                        }

                        return;
                    }
                    JOptionPane.showMessageDialog(frmv, "代码生成过程中出现错误，请仔细检查再次生成！", "错误", JOptionPane.ERROR_MESSAGE);

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(frmv, "出现未知错误！", "错误", JOptionPane.ERROR_MESSAGE);
                } finally {

                    tips.setText("");
                    // 按钮可用
                    btnNewButton.setEnabled(true);
                }

            }
        });

        JButton databaseConfig = new JButton("数据项配置");
        databaseConfig.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                databaseConfig.setEnabled(false);
                tips.setText("当前正在检查数据库配置中，请耐心等待。。。");
            }

            @Override
            public void mouseReleased(MouseEvent e) {

                try {

                    Parameters parameters = checkNeccessary();

                    if (parameters == null) {
                        JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目！填写完毕才可使用数据库配置！", "警告",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    if (DBUtils.getConnection(parameters) == null) {

                        return;
                    }

                    if ("".equals(tableName.getText())) {

                        JOptionPane.showMessageDialog(Constant.frmv, "请先填写数据表的名称再进行配置！", "错误",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    String tipStr = "";
                    String[] tableNameArr = tableName.getText().split("#");

                    String databaseTypeVal = (String) databaseType.getSelectedItem();

                    for (int i = 0; i < tableNameArr.length; i++) {
                        List<String> columnNameList = DBUtils.getColumnNameList(databaseTypeVal, tableNameArr[i],
                                DBUtils.getConnection(parameters));
                        if (columnNameList != null) {
                            continue;
                        }
                        if (i == tableNameArr.length - 1) {
                            tipStr += tableNameArr[i];
                            break;
                        }
                        tipStr += tableNameArr[i] + ",";
                    }

                    // 如果提示不为空，说明有表名填写出现问题
                    if (!"".equals(tipStr)) {
                        JOptionPane.showMessageDialog(frmv,
                                "查询数据表 " + tipStr + " 时出现未知错误！请仔细检查表名是否配置正确（postgresql需要模式名.表名（除public模式））！表名与表名之前是否使用#隔开！", "错误",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    if (ChildWindowConstant.dataBaseConfig == null) {
                        DataBaseConfig.main(parameters);
                        return;
                    }
                    ChildWindowConstant.dataBaseConfig.dispose();
                    ChildWindowConstant.dataBaseConfig = null;
                    DataBaseConfig.main(parameters);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {

                    tips.setText("");
                    databaseConfig.setEnabled(true);

                }
            }
        });

        JLabel label_4 = new JLabel("*");
        label_4.setForeground(Color.RED);

        JLabel label_5 = new JLabel("*");
        label_5.setForeground(Color.RED);

        JCheckBox checkBox = new JCheckBox("大小写敏感");

        GroupLayout groupLayout = new GroupLayout(frmv.getContentPane());
        groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
                .createSequentialGroup().addGap(33)
                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
                        .createSequentialGroup()
                        .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false).addGroup(groupLayout
                                .createSequentialGroup().addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(lblservicenamesid).addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(dataBaseName, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(label_7))
                                .addGroup(groupLayout.createSequentialGroup().addComponent(lblip)
                                        .addPreferredGap(ComponentPlacement.RELATED)
                                        .addComponent(dataBaseIp, GroupLayout.PREFERRED_SIZE, 111,
                                                GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(ComponentPlacement.RELATED).addComponent(lblNewLabel_1)
                                        .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE,
                                                Short.MAX_VALUE)
                                        .addComponent(label_2).addPreferredGap(ComponentPlacement.RELATED)
                                        .addComponent(dataBasePort, GroupLayout.PREFERRED_SIZE, 64,
                                                GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(ComponentPlacement.RELATED).addComponent(label_4)
                                        .addPreferredGap(ComponentPlacement.RELATED)))
                        .addGap(40)
                        .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addGroup(groupLayout.createSequentialGroup().addComponent(label_3)
                                        .addPreferredGap(ComponentPlacement.RELATED)
                                        .addComponent(dataBasePwd, GroupLayout.PREFERRED_SIZE, 88,
                                                GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(ComponentPlacement.RELATED).addComponent(label_5))
                                .addGroup(
                                        groupLayout.createSequentialGroup().addPreferredGap(ComponentPlacement.RELATED)
                                                .addComponent(label_8).addPreferredGap(ComponentPlacement.RELATED)
                                                .addComponent(dataBaseUserName, GroupLayout.PREFERRED_SIZE, 83,
                                                        GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(label_9)))
                        .addGap(10))
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addGroup(groupLayout.createSequentialGroup().addComponent(label_1)
                                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(databaseType,
                                                        GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE))
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                                        .addComponent(lblNewLabel).addComponent(label))
                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
                                                        .addComponent(projectName)
                                                        .addComponent(framework, 0, 101, Short.MAX_VALUE))))
                                .addGap(37)
                                .addComponent(proinfo, GroupLayout.PREFERRED_SIZE, 425, GroupLayout.PREFERRED_SIZE))
                        .addGroup(groupLayout.createSequentialGroup().addComponent(label_10)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(outPath, GroupLayout.PREFERRED_SIZE, 344, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(label_11)
                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(button).addGap(44))
                        .addGroup(groupLayout.createSequentialGroup().addComponent(label_13)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(tableName, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(databaseConfig)
                                .addPreferredGap(ComponentPlacement.RELATED).addComponent(checkBox))
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING).addComponent(themeLable)
                                        .addComponent(label_17))
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addComponent(themeComboBox, GroupLayout.PREFERRED_SIZE, 157,
                                                GroupLayout.PREFERRED_SIZE)
                                        .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
                                                .addComponent(clientStyle, GroupLayout.PREFERRED_SIZE,
                                                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(ComponentPlacement.RELATED, 84, Short.MAX_VALUE)
                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                                        .addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 117,
                                                                GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                .addComponent(lblNewLabel_2)
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(jsFrameWorkComBox,
                                                                        GroupLayout.PREFERRED_SIZE, 98,
                                                                        GroupLayout.PREFERRED_SIZE)
                                                                .addGap(68).addComponent(label_12)
                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                .addComponent(loginConfig, GroupLayout.PREFERRED_SIZE,
                                                                        101, GroupLayout.PREFERRED_SIZE)))
                                                .addGap(67)))))
                .addGap(27))
                .addGroup(groupLayout.createSequentialGroup().addGap(178).addComponent(tips).addContainerGap(476,
                        Short.MAX_VALUE)));
        groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
                .createSequentialGroup()
                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup().addGap(27)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel)
                                        .addComponent(projectName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                                GroupLayout.PREFERRED_SIZE))
                                .addGap(18)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label)
                                        .addComponent(framework, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                                GroupLayout.PREFERRED_SIZE))
                                .addGap(18)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_1)
                                        .addComponent(databaseType, GroupLayout.PREFERRED_SIZE,
                                                GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                        .addGroup(groupLayout.createSequentialGroup().addContainerGap().addComponent(proinfo,
                                GroupLayout.PREFERRED_SIZE, 127, GroupLayout.PREFERRED_SIZE)))
                .addGap(10)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblip).addComponent(label_3)
                        .addComponent(dataBasePwd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_5)
                        .addComponent(dataBaseIp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblNewLabel_1).addComponent(label_2)
                        .addComponent(dataBasePort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_4))
                .addGap(18)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblservicenamesid)
                        .addComponent(dataBaseName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_8)
                        .addComponent(dataBaseUserName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_9, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_7))
                .addGap(18)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_13)
                        .addComponent(tableName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(databaseConfig).addComponent(checkBox))
                .addGap(18)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_10)
                        .addComponent(outPath, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_11).addComponent(button))
                .addGap(27)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_17)
                        .addComponent(clientStyle, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(loginConfig, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_12).addComponent(lblNewLabel_2).addComponent(jsFrameWorkComBox,
                                GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(27)
                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(themeComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)
                        .addComponent(themeLable))
                .addGap(18).addComponent(tips).addPreferredGap(ComponentPlacement.UNRELATED).addComponent(btnNewButton)
                .addContainerGap(128, Short.MAX_VALUE)));
        frmv.getContentPane().setLayout(groupLayout);

        JMenuBar menuBar = new JMenuBar();
        frmv.setJMenuBar(menuBar);

        JMenu menu = new JMenu("皮肤设置");
        menuBar.add(menu);

        JMenuItem hifi = new JMenuItem("灰黑控 √");
        menu.add(hifi);

        JMenuItem blackBuiness = new JMenuItem("黑色商务");
        menu.add(blackBuiness);

        JMenuItem coffee = new JMenuItem("咖啡俏皮");
        menu.add(coffee);

        JMenu highConfig = new JMenu("高级配置");
        menuBar.add(highConfig);

        JMenuItem tablesQuery = new JMenuItem("多表联查配置");
        tablesQuery.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                Parameters parameters = checkNeccessary();

                if (parameters == null) {
                    JOptionPane.showMessageDialog(frmv, "带红色星号的为必填项目！填写完毕才可使用多表联查配置！", "警告", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (DBUtils.getConnection(parameters) == null) {

                    int ifGo = JOptionPane.showConfirmDialog(frmv,
                            "数据库连接失败，请检查配置信息，生成后程序会无法运行,确定继续配置吗？",
                            "提示", JOptionPane.YES_NO_OPTION);
                    if (ifGo != 0) {
                        return;
                    }
                }


                if ("postgresql".equals(parameters.getDataBaseTypeVal())) {
                    JOptionPane.showMessageDialog(frmv, "目前多表查询的postgresql还未测试，生成的代码可能会有问题，会尽快完成哒！", "警告", JOptionPane.ERROR_MESSAGE);
                }

                if (ChildWindowConstant.tablesQuery == null) {
                    TablesQuery.main(parameters);
                    return;
                }

                ChildWindowConstant.tablesQuery.getFrame().dispose();
                ChildWindowConstant.tablesQuery = null;
                TablesQuery.main(parameters);
            }
        });

        JMenuItem loginItem = new JMenuItem("登录功能定制");
        loginItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (ChildWindowConstant.loginConfig == null) {
                    LoginConfig.main();
                    return;
                }
                ChildWindowConstant.loginConfig.getFrame().dispose();
                ChildWindowConstant.loginConfig = null;
                LoginConfig.main();

            }
        });
        highConfig.add(loginItem);

        //自定义实体
        JMenuItem makeEntity = new JMenuItem("自定义实体");
        makeEntity.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (ChildWindowConstant.makeEntity == null) {
                    MakeEntity.main();
                    return;
                }
                ChildWindowConstant.makeEntity.getFrame().dispose();
                ChildWindowConstant.makeEntity = null;
                MakeEntity.main();


            }
        });

        highConfig.add(makeEntity);
        highConfig.add(tablesQuery);

        JMenuItem usualModel = new JMenuItem("常用模块配置");
        usualModel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                JOptionPane.showMessageDialog(frmv, "功能正在开发当中。。。！", "提示", JOptionPane.ERROR_MESSAGE);

            }
        });

        JMenuItem commonParamsMenu = new JMenuItem("常用参数配置");
        commonParamsMenu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (ChildWindowConstant.commonParamsConfig == null) {
                    CommonParamsConfig.main();
                    return;
                }
                ChildWindowConstant.commonParamsConfig.getFrame().dispose();
                ChildWindowConstant.commonParamsConfig = null;
                CommonParamsConfig.main();

            }
        });
        highConfig.add(commonParamsMenu);
        highConfig.add(usualModel);

        JMenu menu_2 = new JMenu("实用工具");
        menuBar.add(menu_2);

        JMenuItem mntmEverything = new JMenuItem("everything");
        mntmEverything.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        UtilDownLoad.main(Constant.everythingZip, Constant.everythingDownLoadDir,
                                Constant.everythingExeName);

                    }
                });

            }
        });
        menu_2.add(mntmEverything);

        JMenuItem mntmDubbo = new JMenuItem("dubbo脚手架");
        mntmDubbo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {

                    File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();

                    String desktopPath = desktopDir.getAbsolutePath() + "/";
                    UtilDownLoad.main(Constant.dubboModelZip, desktopPath, null);
                    showDownLoadMsg();

                } catch (Exception e1) {

                }

            }

        });
        menu_2.add(mntmDubbo);

        JMenuItem mntmSpringcloud = new JMenuItem("springcloud脚手架");
        mntmSpringcloud.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {

                    File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();

                    String desktopPath = desktopDir.getAbsolutePath() + "/";
                    UtilDownLoad.main(Constant.cloudModelZip, desktopPath, null);

                    showDownLoadMsg();

                } catch (Exception e1) {

                }

            }
        });
        menu_2.add(mntmSpringcloud);

        JMenu versionUpdate = new JMenu("版本特性");

        menuBar.add(versionUpdate);

        JMenuItem menuItem = new JMenuItem("查看本次更新");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frmv,
                        "本次更新：多表配置优化，新增自定义实体功能（高级配置——》自定义实体）！" + CodeConstant.NEW_LINE
                                + "目前已支持一键生成项目导入eclipse/idea运行，不断完善中！" + CodeConstant.NEW_LINE
                                + "后续更新：更多个性化配置，更加灵活的生成代码！" + CodeConstant.NEW_LINE + "敬请期待！",
                        "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        versionUpdate.add(menuItem);

        JMenuItem menuItem_3 = new JMenuItem("打赏作者");
        menuItem_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                if (ChildWindowConstant.callGood == null) {
                    CallGood.main(new String[]{});
                    return;
                }
                ChildWindowConstant.callGood.dispose();
                ChildWindowConstant.callGood = null;
                CallGood.main(new String[]{});
            }
        });
        versionUpdate.add(menuItem_3);

        for (int i = 0; i < menu.getItemCount(); i++) {

            menu.getItem(i).addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    JMenuItem item = (JMenuItem) e.getSource();

                    String skinName = item.getText();

                    // 设置当前皮肤为已选择
                    skinName = skinName.replaceAll(CodeConstant.yesChoose, "") + CodeConstant.yesChoose;

                    item.setText(skinName);

                    // 遍历设置其他元素为未选择
                    for (int j = 0; j < menu.getItemCount(); j++) {

                        String otherSkinName = menu.getItem(j).getText();
                        if (!skinName.equals(otherSkinName)) {
                            menu.getItem(j).setText(otherSkinName.replaceAll(CodeConstant.yesChoose, ""));
                        }
                    }

                    // 设置皮肤
                    try {
                        if (skinName.contains("灰黑控")) {
                            UIManager.setLookAndFeel(
                                    org.pushingpixels.substance.api.skin.SubstanceGraphiteLookAndFeel.class.getName());
                            proinfo.setForeground(null);
                        } else if (skinName.contains("黑色商务")) {
                            UIManager.setLookAndFeel(
                                    org.pushingpixels.substance.api.skin.SubstanceBusinessBlackSteelLookAndFeel.class
                                            .getName());
                            proinfo.setForeground(Color.BLACK);
                        } else if (skinName.contains("咖啡俏皮")) {
                            UIManager.setLookAndFeel(
                                    org.pushingpixels.substance.api.skin.SubstanceCremeCoffeeLookAndFeel.class
                                            .getName());
                            proinfo.setForeground(Color.BLACK);
                        }

                        Constant.frmv.validate();
                        // 重绘
                        Constant.frmv.repaint();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            });
        }

    }

    // 弹出框放到UtilDownLoad会报错，只能这样了
    private void showDownLoadMsg() {

        while (true) {
            if (UtilDownLoad.downFlag) {
                JOptionPane.showMessageDialog(frmv, "拉取成功！已下载到桌面", "提示", JOptionPane.INFORMATION_MESSAGE);
                UtilDownLoad.downFlag = false;
                break;
            }
        }

    }

    private boolean dealDymaicAndStaticUser(String loginItem) {
        if ("静态用户".equals(loginItem)) {

            if (ChildWindowConstant.user1.size() == 0 && ChildWindowConstant.user2.size() == 0
                    && ChildWindowConstant.user3.size() == 0) {
                ChildWindowConstant.user1.add("admin");
                ChildWindowConstant.user1.add("root");
            }

        } else if ("动态用户".equals(loginItem)) {

            if (ChildWindowConstant.dynamicUserList.size() == 0) {

                JOptionPane.showMessageDialog(frmv, "检测到你没有进行动态用户的配置，请先配置！", "提示", JOptionPane.INFORMATION_MESSAGE);

                if (ChildWindowConstant.loginConfig == null) {
                    LoginConfig.main();
                    return false;
                }
                ChildWindowConstant.loginConfig.getFrame().dispose();
                ChildWindowConstant.loginConfig = null;
                LoginConfig.main();
                return false;
            }
        }
        return true;
    }

    /**
     * 检查必填项目
     *
     * @return
     */
    private Parameters checkNeccessary() {

        String dataBaseIpVal = dataBaseIp.getText();

        String dataBasePortVal = dataBasePort.getText();

        String dataBasePwdVal = dataBasePwd.getText();

        String dataBaseNameVal = dataBaseName.getText();

        String dataBaseUserNameVal = dataBaseUserName.getText();

        String tableNameVal = tableName.getText();

        String outPathVal = outPath.getText();

        if ("".equals(dataBaseIpVal) || "".equals(dataBasePortVal) || "".equals(dataBasePwdVal)
                || "".equals(dataBaseNameVal) || "".equals(dataBaseUserNameVal) || "".equals(outPathVal)) {
            return null;
        }

        Parameters parameters = new Parameters();

        parameters.setDataBaseTypeVal((String) databaseType.getSelectedItem());
        parameters.setDataBaseIpVal(dataBaseIpVal);
        parameters.setDataBasePortVal(dataBasePortVal);
        parameters.setDataBasePwdVal(dataBasePwdVal);
        parameters.setDataBaseNameVal(dataBaseNameVal);
        parameters.setDataBaseUserNameVal(dataBaseUserNameVal);
        parameters.setTableName(tableNameVal);
        parameters.setOutPathVal(outPathVal);

        return parameters;

    }
}
